<template>
  <component
    :is="currentComponent"
    class="svg-icon"
    aria-hidden="true"
    :style="'width:' + svgSize + ';height:' + svgSize"
    :color="color"
  ></component>
</template>

<script lang="ts" setup>
import type { Component } from 'vue'
import { computed } from 'vue'

const props = withDefaults(
  defineProps<{
    name: string
    color?: string
    size?: number | string
  }>(),
  {
    color: '',
    size: '1em'
  }
)

const modules = import.meta.glob('@/assets/icons/*.svg', {
  query: '?component',
  eager: true
})

const formatSize = (size: number | string) => {
  return typeof size === 'number' ? `${size}px` : size
}

const newName = computed(() => {
  return props.name.toLowerCase()
})

const svgSize = computed(() => formatSize(props.size))

// 获取对应svg组件
const currentComponent = computed(() => {
  const fileName = `/${newName.value}.svg`

  let findMod: Component | undefined = undefined

  for (const path in modules) {
    const mod = modules[path]
    if (path.endsWith(fileName)) {
      findMod = mod as Component
    }
  }

  return findMod
})
</script>
<style lang="scss" scoped>
.svg-icon {
  display: inline-block;
  width: 1em;
  height: 1em;
  overflow: hidden;
  vertical-align: -0.15em; /* 因icon大小被设置为和字体大小一致，而span等标签的下边缘会和字体的基线对齐，故需设置一个往下的偏移比例，来纠正视觉上的未对齐效果 */
  outline: none;
  fill: currentcolor; /* 定义元素的颜色，currentColor是一个变量，这个变量的值就表示当前元素的color值，如果当前元素未设置color值，则从父元素继承 */
}
</style>
